package cn.web.demo.service.impl;

import cn.web.demo.mapper.PermissionMapper;
import cn.web.demo.model.Permission;
import cn.web.demo.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class IPermissionServiceImpl implements IPermissionService {

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public List<Permission> findMenuList() {
        return permissionMapper.findAllMenus();
    }

    @Override
    public List<Permission> findAllPermission() {
        return permissionMapper.findAllPermission();
    }

    @Override
    public List<Permission> findAllParentMenus() {
        return permissionMapper.findAllParentMenus();
    }

    @Override
    public void save(Permission permission) {
        //保存权限
//        Permission{id=0, name='AA', path='/AA/list',
//                authorization_flag='READ', parent_id=0,
//                is_menu=1, z_index=0}
        //1.更改authorization_flag
        if(permission.getParent_id() == 0) {//如果是根菜单/节点，授权标识和路径都是为NULL
            permission.setAuthorization_flag(null);
            permission.setPath(null);
        }else{
            String[] strArr = permission.getPath().split("/");
            System.out.println("strArr size:" + strArr.length);
            String af = permission.getAuthorization_flag() + "_" + strArr[1];
            permission.setAuthorization_flag(af.toUpperCase());
        }
        //2.设置z_index
        //如果根菜单 z_index的最大值+1
        if(permission.getParent_id() == 0){
            int maxZIndex = permissionMapper.getMaxZIndex() + 1;
            permission.setZ_index(maxZIndex);
        }else{
            //否则就是父节点的z_index
            //通过id找到节点
            Permission parentNode = permissionMapper.findAllPermissionById(permission.getParent_id());
            permission.setZ_index(parentNode.getZ_index());
        }

        //3.插入db
        //System.out.println("插入的数据:" + permission);

        permissionMapper.save(permission);
    }

    @Override
    public List<Permission> findPermissionListByUserId(Integer userId) {
        return permissionMapper.findPermissionListByUserId(userId);
    }
}
